package com.deepblue.image.maker.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;

/**
 * websocket处理器
 *
 * @author yymagicer
 * @version 1.0
 * @date 2021/11/10 下午2:42
 */
@Slf4j
public class WebSocketHandler extends TextWebSocketHandler {



    private WebsocketSessionCache websocketSessionCache;


    public WebSocketHandler(){

    }

    public WebSocketHandler(WebsocketSessionCache websocketSessionCache){
        this.websocketSessionCache = websocketSessionCache;
    }

    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message)
            throws IOException {
        log.info("获取到消息 >> {} " ,message.getPayload());
        session.sendMessage(new TextMessage(String.format("收到用户：【%s】发来的【%s】",
                session.getAttributes().get("uid"), message.getPayload())));
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws
            Exception {
        log.info("获取到拦截器中用户ID : {}" , session.getAttributes().get("uid"));
        String uid = session.getAttributes().get("uid").toString();
        websocketSessionCache.set(uid, session);
        addOnlineCount();
        log.info(" {} 加入webSocket！当前人数为 {}" ,uid, websocketSessionCache.get());
        session.sendMessage(new TextMessage("欢迎连接到ws服务! 当前人数为：" + websocketSessionCache.get()));
    }


    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status)
            throws Exception {
        log.info("断开连接!");
        String uid = session.getAttributes().get("uid").toString();
        websocketSessionCache.remove(uid);
        subOnlineCount();
    }

    /**
     * 添加链接人数
     */
    public  void addOnlineCount() {
        websocketSessionCache.incrementAndGet();
    }

    /**
     * 移除链接人数
     */
    public  void subOnlineCount() {
        websocketSessionCache.decrementAndGet();
    }
}
